package com.example.blog.controller;

import com.example.blog.entity.Article;
import com.example.blog.mapper.ArticleMapper;
import com.example.blog.repository.ArticleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.ui.Model;
import java.util.List;

@Controller
@RequestMapping
public class SearchCtl {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private ArticleRepository articleRepository;
    @GetMapping("/search")
    public String search(@RequestParam("query") String query,
                         @RequestParam(name = "page", defaultValue = "0") int page,
                         Model model){
        int size = 4;
        Pageable pageable = PageRequest.of(page, size);
        Page<Article> articles = articleRepository.findAllByTitleContainingIgnoreCase(query, pageable);
        model.addAttribute("articles", articles.getContent());
        model.addAttribute("currentPage", articles.getNumber());
        model.addAttribute("totalPages", articles.getTotalPages());
        model.addAttribute("totalElements", articles.getTotalElements());
        model.addAttribute("query",query);
        return "searchList";
    }



}